package com.teemor.common.bean.utils.redis;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Description:
 * @author zhoulk
 * @date: 2020/3/3
 */
class RedisClient {

    private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
    private String redisAddr = "127.0.0.1";
    private int port = 6379;
    private int expire = 0;
    private String AUTH = "zlk123789456.."; //redis密码，通过服务器里redis配置文件里设置
    private int MAX_TOTAL = 3000;//最大连接数
    private int MAX_IDLE = 2000;//最大空闲连接数
    private int MAX_WAIT = 1000000;//等待可用连接的最大时间，单位毫秒，默认值为-1，表示永不超时。如果超过等待时间，则直接抛出
    private int TIMEOUT = 1000000; //在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
    private boolean TEST_ON_BORROW = true;
    private JedisPool jedisPool = null;

    RedisClient(String host, int port, String auth) {
        String redisAddr = StringUtils.isBlank(host) ? this.redisAddr : host;
        port = port <= 0 ? this.port : port;
        this.AUTH = StringUtils.isNotBlank(auth) ? this.AUTH : auth;
        StringBuilder sb = new StringBuilder();

        sb.append("--redisPool init").append("\n");
        sb.append("--配置信息如下:").append("\n").append("\n");
        sb.append("--redisAddr:{}").append(redisAddr).append("\n");
        sb.append("--port:").append(port).append("\n");
        sb.append("--MAX_TOTAL:").append(MAX_TOTAL).append("\n");
        sb.append("--MAX_IDLE:").append(MAX_IDLE).append("\n");
        sb.append("--MAX_WAIT:").append(MAX_WAIT).append("\n");
        sb.append("--TIMEOUT:").append(TIMEOUT).append("\n");
        sb.append("--配置信息打印结束--").append("\n");
        logger.info(sb.toString());

        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(MAX_TOTAL);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT);
            if (StringUtils.isNotBlank(AUTH))
                jedisPool = new JedisPool(config, redisAddr, port, TIMEOUT, AUTH);  // 有密码的情况
            else
                jedisPool = new JedisPool(config, redisAddr, port, TIMEOUT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    synchronized Jedis getJedis() {
        //连接池中获取资源
        try {
            if (jedisPool != null) {
                return jedisPool.getResource();
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //释放jedis和jedisPool资源
    void releaseResource(final Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
//        if (jedisPool != null) {
//            jedisPool.close();
//        }
    }


}
